// pages/categoryMoney/categoryMoney.js
var app = getApp()
var util = require('../../utils/util.js');
const url = util.baseUrl
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isRecommendRelation:false,//是否调用绑定关系的接口
    userInfo: '', //用户信息
    mohuanUser: '', //用户id
    phoneNo: '', // 扫描推广码进入客户的推荐人手机号
    discountId:'',//折扣信息
    memberId: '',
    scene: [],
    index: 0,
    status: false,
    inputCates: '我需要的品类',
    inputMoney: '我的预算金额及数量',
    inputOccasion: '我要穿着使用的场合',
    inputOther: '备注（例：其他场合使用）',
    selectedCateList: [],
    scenes: 0, //选择的场景
    requirementId: '', //需求id
    successSubmit: 1,
    blackText: false,
    mustSelected: 0, //穿着场合必填字段标识
    disabled: true,
    btnTxt: '提交需求进入在线交流',
    rebackMarks: false,
    height: app.globalData.deviceInfo.windowHeight,
    isLogin:false
  },
  // 用户如果为登录跳转登录注册页面
  gologin: function(e) { //登录
    wx.navigateTo({
      url: '../login/login',
      success: function(res) {},
      fail: function() {},
      complete: function() {}
    })
  },
  // 绑定备注表单事件
  bindremarksInput: function(e) {
    this.setData({
      inputOther: e.detail.value
    })
    if (e.detail.value == '') {
      inputOther: '备注（例：其他场合使用）'
    }
    console.log(444)
  },
  //  选择场景
  bindPickerChange: function(e) {
    var that = this
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      inputOccasion: this.data.scene[e.detail.value],
      blackText: true,
      mustSelected: 1,
    })
    console.log('====' + that.data.selectedCateList.length)
    console.log('====' + that.data.mustSelected)
    if (that.data.selectedCateList.length > 0 && that.data.mustSelected == 1) {
      that.setData({
        disabled: false
      })
    }
  },
  // 客服消息回调测试
  ceshi: function() {
    console.log('测试')
  },
  // 打开授权测试页回调
  ceshiyemian: function() {
    console.log('授权测试页回调测试')
  },
  // 提交需求
  submitInputBox: function(e) {
    wx.setStorage({
      key: 'IsClickContact',
      data: '1',
    })

    var isClickContact = wx.getStorageSync("IsClickContact");
    console.log("==contact isclickcontact==" + isClickContact)

    var that = this
    console.log('=====' + that.data.selectedCateList)
    // 判断是否必填表单    
    if (that.data.selectedCateList == "") {
      wx.showToast({
        title: '请选择品类',
        icon: 'loading',
        duration: 500
      })
    } else if (that.data.mustSelected == 0) {
      wx.showToast({
        title: '请选择穿着场合',
        icon: 'loading',
        duration: 500
      })
    } else {
      // 表单需要的参数      
      var params = {
        recommender: that.data.phoneNo, //推荐人手机号
        memberId: that.data.memberId, //用户id
        demandId: that.data.requirementId, //需求id
        categoryId: that.data.selectedCateList[0].sortid, //品类id
        userCategory: that.data.inputCates, //用户所选的品类
        totalBudget: that.data.inputMoney, //总的金额
        budgets: that.data.selectedCateList, //品类列表
        dressOccasion: that.data.inputOccasion, //工作changjing
        remark: that.data.inputOther, //备注
        discount:that.data.discountId,//推广人员折扣信息
      }
      console.log(params)
      console.log('定制页面提交的参数')
      var mohuanUser = app.globalData.mohuanUser
      var token = mohuanUser["X-AUTH-TOKEN"]
      console.log(token)
      wx.request({
        url: url + '/c2mwebservice/api/v2/customization/addDemand', //仅为示例，并非真实的接口地址
        data: params,
        method: 'POST',
        header: {
          'content-type': 'application/json', // 默认值
          'X-AUTH-TOKEN': token,
        },
        success(res) {
          console.log(res.data)
          wx.showToast({
            title: '提交成功',
          })
          // 清楚推广人员手机号和折扣信息
          wx.removeStorage({
            key: 'phoneNo',
            success: function (res) { },
          })
          wx.removeStorage({
            key: 'discountId',
            success: function (res) { },
          })
          // 清楚选择缓存列表
          // wx.removeStorageSync('selectedCateList')
          wx.removeStorage({
            key: 'selectedCateList',
            success: function(res) {},
          })
          // wx.removeStorage('selectedCateList')
          console.log('==清楚缓存信息缓存信息==' + wx.getStorageSync('selectedCateList'))
        }
      })
    }


  },
  /**
   * 时间处理函数
   */
  goCategory: function() {
    wx.navigateTo({
      url: '/pages/categoryMoney/categoryMoney',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this
    that.setData({
      userInfo: app.globalData.userInfo,
      mohuanUser: app.globalData.mohuanUser,

    })
    // 获取页面参数
    console.log(options)   
    console.log('扫码进入获取页面参数')    
    if(options.scene){//通过扫码进来
      var scene = decodeURIComponent(options.scene)
      console.log('转码后的url')
      console.log(scene)
      var arrParamInfo = scene.split('&')
      for (var i = 0; i < arrParamInfo.length; i++){
        var arr = arrParamInfo[i].split('=')
        if (arr[0] == 'phoneNo'){
          that.setData({
            phoneNo: arr[1]
          })
        } else if (arr[0] == 'discount'){
          that.setData({
            discountId: arr[1]
          })
        }       
      }
      console.log(that.data.phoneNo)
      console.log('新版营销推广人员手机号')
      console.log(that.data.phoneNo)
      console.log('新版营销推广人员折扣信息')      
      console.log(that.data.discountId) 
      // 二维码参数里面获取的推广人员手机号和折扣信息如果没有的话就赋值为空 防止提交需求是参数错误
      if (that.data.phoneNo == undefined) {
        that.setData({
          phoneNo: ''
        })
      }
      if (that.data.discountId == undefined) {
        that.setData({
          discountId: ''
        })
      }   
      //缓存推荐人手机号 在品类页面其他区调用
      wx.setStorageSync('phoneNo', that.data.phoneNo)
      //缓存推荐人的折扣信息在团购区和公益区以及其他区使用
      wx.setStorageSync('discountId', that.data.discountId)   
    }
    // 用户已登录--调用绑定关系的接口
    if (that.data.mohuanUser != null) {
      that.data.memberId = that.data.mohuanUser.memberId
      console.log(that.data.mohuanUser)
    }
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },



  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this
    var mohuanUserStorge = wx.getStorageSync('userdata')
    console.log('刚进入页面获取全局变量')
    console.log(mohuanUserStorge.memberId)
    that.setData({
      mohuanUser: mohuanUserStorge,   
    })
    // 用户已登录
    if (mohuanUserStorge !=''){
      that.setData({
        isLogin: true,
      })
      // 调用绑定关系接口 扫码进来且登录状态
      // debugger
      var mohuanUserStorge = wx.getStorageSync('userdata')
      var token = mohuanUserStorge["X-AUTH-TOKEN"]
      if (that.data.phoneNo !=''){//没有推广人员手机号 不是通过扫码进来的    
      var paramsData = {
        memberId: mohuanUserStorge.memberId,
        recommenderPhone: that.data.phoneNo
      }
        wx.request({
          header: {
            'X-AUTH-TOKEN': token
          },
          url: url + '/c2mwebservice/api/v2/customization/recommendRelation/add',
          method: 'post',
          data: paramsData,
          success: res => {
            // console.log(res)
            if (res.data.returnData == 'N') {
              wx.showToast({
                title: '扫描成功',
                icon: 'success'
              })
            } else {
              // wx.showToast({
              //   title: '扫码失败',
              //   icon: 'success'
              // }) 
            }
          }
        })
      }else{
      var paramsData = {
          memberId: mohuanUserStorge.memberId        
        }
      }   

    }else{//用户未登录
      that.setData({
        isLogin: false,
      })
    }
    console.log(that.data.mohuanUser.memberId) 
    wx.getSetting({
      success: res => {
        console.log('=======用户授权结果=======')
        console.log(res.authSetting)
      }
    })
    // 获取页面参数--推荐人手机号
    console.log('推荐人手机号' + that.data.phoneNo)
    // 点击客服返回操作
    var isClickContact = wx.getStorageSync("IsClickContact");
    console.log("== isclickcontact==" + isClickContact)
    if (isClickContact == "1") {
      console.log("Huqudaocontact")
      wx.removeStorage({
        key: 'IsClickContact',
        success: function(res) {},
      })
      that.setData({
        btnTxt: '需求已提交请等待回复',
        blackText: false,
        scene: [],
        rebackMarks: false,
      })

    } else {
      console.log('weihuoqudaocontact')
      that.setData({
        inputCates: '我需要的品类',
        inputMoney: '我的预算金额及数量',
        inputOccasion: '我要穿着使用的场合',
        inputOther: '备注（例：其他场合使用）',
        inputTxt: '',
        blackText: false,
        rebackMarks: true,
        btnTxt: '提交需求进入在线交流',
      })
      console.log('===备注颜色true ===' + that.data.blackText)

    }
    console.log(that.data.disabled)
    that.setData({
      userInfo: app.globalData.userInfo,
      mohuanUser: app.globalData.mohuanUser,
      disabled: true
    })
    // 用户已登录
    if (that.data.mohuanUser != null) {
   
      that.data.memberId = that.data.mohuanUser.memberId
      console.log(that.data.mohuanUser)
      // console.log('用户id')
      // 获取所选品类缓存列表
      var selectedCateListStorage = wx.getStorageSync('selectedCateList')
      that.setData({
        selectedCateList: selectedCateListStorage
      })
      console.log('====初始化页面获取缓存列表===' + that.data.selectedCateList.length)

      if (that.data.selectedCateList == "") {
        that.setData({
          disabled: true
        })
      }
      console.log('选择品类的列表')
      console.log(that.data.selectedCateList.length)
      // 定制页面表单显示选中的品类
      if (that.data.selectedCateList.length > 0) {
        var inputCate = ''
        var inputCateItem = ''

        var inputMoneyitemArry = []
        var inputMoneymax = 0
        var inputMoneymin = 0
        var totalMoney = ''


        var inputNumber = 0
        var inputNumberitem = ''

        for (var i = 0; i < that.data.selectedCateList.length; i++) {
          inputCateItem += that.data.selectedCateList[i].catename + '、' //品类
          inputNumberitem = that.data.selectedCateList[i].numbers.replace(/[^0-9]/ig, "") //数量
          inputNumber += parseInt(inputNumberitem) //件数相加
          // 金额
          //  单价去掉前面的单件两个数字
          var inputMoneyitemStringLength = that.data.selectedCateList[i].price.length
          var inputMoneyitemString = that.data.selectedCateList[i].price.slice(4, inputMoneyitemStringLength)
          // console.log(inputMoneyitemString)
          // console.log('获取的价格字符串')
          inputMoneyitemArry = inputMoneyitemString.split('-')
          inputMoneymin += parseInt(inputMoneyitemArry[0]) * parseInt(inputNumberitem)
          inputMoneymax += parseInt(inputMoneyitemArry[1]) * parseInt(inputNumberitem)
        }
        inputCate = that.data.selectedCateList[0].sortname + ':' + inputCateItem //品类      
        var length = inputCate.length - 1
        console.log(length)

        var inputCates = inputCate.substring(0, length)
        // console.log(inputCate)

        //总金额和总数量
        var numberString = ' 数量：' + inputNumber
        var totalMoney = '预算：' + inputMoneymin + '-' + inputMoneymax + numberString
        console.log(totalMoney)
        // 删除品类最后一个顿号
        that.setData({
          // inputCates: inputCate.substring(0, inputCate.Length - 1)
          inputCates: inputCates,
          inputMoney: totalMoney
        })
        //  获取场合列表   
        that.data.scenes = that.data.selectedCateList[0].sortid
        util.getSenceList(`/c2mwebservice/api/v2/public/customization/getDressOccasion/` + that.data.scenes, function(res) {
          console.log(res)
          if (res.returnCode == '200') {
            that.setData({
              scene: res.returnData.dressOccasion
            })
          }
        }, function(error) {
          console.log(error)
          wx.hideToast()
        })

        //  获取需求id  
        util.getrequirementId(`/c2mwebservice/api/v2/public/customization/getDemandId`, function(res) {
          // console.log(res)
          if (res.returnCode == '200') {
            that.data.requirementId = res.returnData.demandId
            that.setData({
              requirementId: res.returnData.demandId
            })
          }
          console.log(that.data.requirementId)
        }, function(error) {
          console.log(error)
          wx.hideToast()
        })


      }


    }




  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    console.log('======= hide ==========')
    wx.removeStorage({
      key: 'selectedCateList',
      success: function(res) {},
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})